/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.org;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.controller.CommonPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.exception.AccountException;
import com.je.rbac.service.account.RbacAccountService;
import com.je.rbac.service.company.RbacDepartmentUserService;
import com.je.rbac.service.organization.RbacOrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/je/rbac/cloud/developer")
public class RbacOrgUserManagerController extends CommonPlatformController {

    @Autowired
    private RbacOrganizationService rbacOrganizationService;
    @Autowired
    private RbacDepartmentUserService rbacDepartmentUserService;

    @Override
    @RequestMapping(value = "/load", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "外部机构管理模块",operateTypeCode = "loadDevelopManage",operateTypeName = "查看外部机构管理",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        return super.load(param, request);
    }

    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "外部机构管理模块",operateTypeCode = "updateDevelopManage",operateTypeName = "更新外部机构管理",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        try {
            //同步账号表数据
            rbacOrganizationService.syncAccountBy(dynaBean);
        }catch (AccountException e){
            return BaseRespResult.errorResult(e.getMessage());
        }
        //若用户名称发生修改，则同步更新全局该用户名称
        rbacOrganizationService.updateUserName(dynaBean);
        return BaseRespResult.successResult(manager.doUpdate(param, request).getValues());
    }

    @Override
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "外部机构管理模块",operateTypeCode = "removeDevelopManage",operateTypeName = "移除外部机构管理",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        //同步移除全局该外部用户信息
        rbacDepartmentUserService.syncRemoveUserMsg(dynaBean.getPkValue());
        return BaseRespResult.successResult(String.format("%s 条记录被删除", manager.doRemove(param, request)));
    }

    /***
     * 保存
     * @param param
     * @param request
     * @return
     */
    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "外部机构管理模块",operateTypeCode = "saveDevelopManage",operateTypeName = "保存外部机构管理",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        //同步创建账号 状态默认为 禁用
        String tableCode = getStringParameter(request, "tableCode");
        if (Strings.isNullOrEmpty(tableCode)) {
            return BaseRespResult.errorResult("请选择要开通账号的相关人员表编码！");
        }
        //通过 tableCode 获取机构orgId
        DynaBean orgBean = rbacOrganizationService.getOrgByTableCode(tableCode);
        if (orgBean == null) {
            return BaseRespResult.errorResult("该人员表绑定的机构不存在，请检查是否绑定机构！");
        }
        if (orgBean.getStr("SY_STATUS").equals("0")) {
            return BaseRespResult.errorResult("该人员表绑定的机构已禁用，请先启用！");
        }
        DynaBean savedBean = manager.doSave(param, request);
        String orgId = orgBean.getStr("JE_RBAC_ORG_ID");
        String tableIdCode = orgBean.getStr("ORG_FIELD_PK");
        String userId = savedBean.getStr(tableIdCode);
        rbacOrganizationService.openAccount(orgId, userId, "0");
        return BaseRespResult.successResult(savedBean.getValues());
    }

    /**
     * 外部机构用户操作
     * 允许访问：enableAccess，禁止访问：disableAccess，启用：enable，禁用：disable，删除：delete
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/operationUser"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "外部机构管理模块",operateTypeCode = "operateDevelopManage",operateTypeName = "外部机构允许/禁止访问系统",logTypeCode = "systemManage",logTypeName = "系统管理")
    public BaseRespResult operationUser(HttpServletRequest request) {
        //操作类型
        String opType = getStringParameter(request, "opType");
        String tableCode = getStringParameter(request, "tableCode");
        String userIds = getStringParameter(request, "userIds");
        if (Strings.isNullOrEmpty(opType)) {
            return BaseRespResult.errorResult("请选择要操作的类型！");
        }
        if (Strings.isNullOrEmpty(tableCode)) {
            return BaseRespResult.errorResult("请选择要操作的相关人员表编码！");
        }
        if (Strings.isNullOrEmpty(userIds)) {
            return BaseRespResult.errorResult("请选择要操作的相关人员！");
        }
        //通过 tableCode 获取机构orgId
        DynaBean orgBean = rbacOrganizationService.getOrgByTableCode(tableCode);
        if (orgBean == null) {
            return BaseRespResult.errorResult("该人员表绑定的机构不存在，请检查是否绑定机构！");
        }

        String orgId = orgBean.getStr("JE_RBAC_ORG_ID");
        try {
            rbacOrganizationService.operationUserWithAccount(opType, orgId, userIds);
        } catch (Exception e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult("操作成功！");
    }

    @Override
    @RequestMapping(value = "/doCopy", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doCopy(BaseMethodArgument param, HttpServletRequest request) {
        return BaseRespResult.successResult(manager.doCopy(param, request).getValues());
    }

}
